package user.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.xfengshopping.MainActivity;
import com.example.xfengshopping.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

import LOGIN.login;
import utils.TokenUtils;

public class AccountManagement extends AppCompatActivity {
    private static final String TAG = "AccountManagement";
    private static final String PREFS_NAME = "AppPrefs";

    private EditText nicknameEditText;
    private EditText introduceSignEditText;
    private EditText passwordEditText;
    private Button saveButton;
    private Button exitButton;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account_management);

        sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        initViews();

        // 优先从网络获取用户信息
        fetchUserInfo();

        // 后退按钮逻辑
        ImageView backMy = findViewById(R.id.account_management_back);
        backMy.setOnClickListener(v -> {
            Intent intent = new Intent(AccountManagement.this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            finish();
        });
    }

    private void initViews() {
        nicknameEditText = findViewById(R.id.nickname);
        introduceSignEditText = findViewById(R.id.introduceSign);
        passwordEditText = findViewById(R.id.passwordMd5);
        saveButton = findViewById(R.id.save);
        exitButton = findViewById(R.id.exit);

        saveButton.setOnClickListener(v -> updateUserInfo());
        exitButton.setOnClickListener(v -> {
            // 1. 清除所有 Token 和用户数据
            TokenUtils.clearToken(AccountManagement.this); // 清除 Token

            // 2. 清除 SharedPreferences 中的用户信息（可选）
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear(); // 清空所有 SharedPreferences 数据
            editor.apply();

            // 3. 跳转到登录页，并清空 Activity 栈
            Intent intent = new Intent(AccountManagement.this, login.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // 清空栈
            startActivity(intent);
            finish(); // 结束当前 Activity
        });
    }

    // 从网络获取用户信息
    private void fetchUserInfo() {
        new FetchUserInfoTask().execute();
    }

    // 保存用户信息到网络和本地
    private void updateUserInfo() {
        String nickName = nicknameEditText.getText().toString();
        String introduceSign = introduceSignEditText.getText().toString();
        String rawPassword = passwordEditText.getText().toString();
        String passwordMd5 = md5(rawPassword);

        // 先更新到网络
        new UpdateUserInfoTask().execute(nickName, introduceSign, passwordMd5);

        // 同时保存到本地
        saveUserInfoLocally(nickName, introduceSign);
    }

    // 保存用户信息到本地
    private void saveUserInfoLocally(String nickname, String signature) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("nickname", nickname);
        editor.putString("signature", signature);
        editor.apply();
    }

    private String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            Log.e(TAG, "MD5加密失败", e);
            return "";
        }
    }

    // 异步任务：从网络获取用户信息
    private class FetchUserInfoTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... voids) {
            String token = TokenUtils.getToken(AccountManagement.this);
            if (token == null || token.isEmpty()) {
                return null;
            }

            HttpURLConnection conn = null;
            BufferedReader reader = null;
            try {
                URL url = new URL("http://47.99.134.126:28019/api/v1/user/info");
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("token", token);
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = conn.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    return response.toString();
                } else {
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                try {
                    JSONObject jsonResponse = new JSONObject(result);
                    JSONObject data = jsonResponse.getJSONObject("data");
                    nicknameEditText.setText(data.getString("nickName"));
                    introduceSignEditText.setText(data.getString("introduceSign"));

                    // 同时更新本地存储
                    saveUserInfoLocally(
                            data.getString("nickName"),
                            data.getString("introduceSign")
                    );
                } catch (JSONException e) {
                    Toast.makeText(AccountManagement.this, "解析用户信息失败", Toast.LENGTH_SHORT).show();
                    // 解析失败时，尝试从本地加载
                    loadUserInfoFromLocal();
                }
            } else {
                Toast.makeText(AccountManagement.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
                // 获取失败时，尝试从本地加载
                loadUserInfoFromLocal();
            }
        }
    }

    // 从本地加载用户信息（网络请求失败时使用）
    private void loadUserInfoFromLocal() {
        String nickname = sharedPreferences.getString("nickname", "未设置昵称");
        String signature = sharedPreferences.getString("signature", "暂无个性签名");
        nicknameEditText.setText(nickname);
        introduceSignEditText.setText(signature);
    }

    // 异步任务：更新用户信息到网络
    private class UpdateUserInfoTask extends AsyncTask<String, Void, Boolean> {
        @Override
        protected Boolean doInBackground(String... params) {
            String token = TokenUtils.getToken(AccountManagement.this);
            if (token == null || token.isEmpty()) {
                return false;
            }

            String nickName = params[0];
            String introduceSign = params[1];
            String passwordMd5 = params[2];

            HttpURLConnection conn = null;
            BufferedWriter writer = null;
            try {
                URL url = new URL("http://47.99.134.126:28019/api/v1/user/info");
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("PUT");
                conn.setRequestProperty("token", token);
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);

                JSONObject requestBody = new JSONObject();
                requestBody.put("nickName", nickName);
                requestBody.put("introduceSign", introduceSign);
                requestBody.put("passwordMd5", passwordMd5);

                OutputStream outputStream = conn.getOutputStream();
                writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
                writer.write(requestBody.toString());
                writer.flush();

                int responseCode = conn.getResponseCode();
                return responseCode == HttpURLConnection.HTTP_OK;
            } catch (IOException | JSONException e) {
                e.printStackTrace();
                return false;
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }

        @Override
        protected void onPostExecute(Boolean success) {
            if (success) {
                Toast.makeText(AccountManagement.this, "更新成功", Toast.LENGTH_SHORT).show();
                passwordEditText.setText(""); // 清空密码框
            } else {
                Toast.makeText(AccountManagement.this, "更新失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}